from flask import Flask, request, send_from_directory, jsonify
from flask_cors import CORS
from flask_socketio import SocketIO
import os

# 导入数据库配置和模型
from database.config import init_database
from database.models import Base

# 导入路由
from routes.knowledge_base_routes import kb_bp
from routes.document_routes import doc_bp
from routes.auth_routes import auth_bp

# 导入文件解析模块
from file_parser import parse_file
import hashlib

app = Flask(__name__)
CORS(app)  # 允许跨域请求
socketio = SocketIO(app, cors_allowed_origins="*")

# 文件存储目录
UPLOAD_FOLDER = 'uploads'
os.makedirs(UPLOAD_FOLDER, exist_ok=True)

# 注册路由蓝图
app.register_blueprint(kb_bp, url_prefix='/api/v1')
app.register_blueprint(doc_bp, url_prefix='/api/v1')
app.register_blueprint(auth_bp, url_prefix='/api/v1')

# 健康检查端点
@app.route('/api/v1/health', methods=['GET'])
def health_check():
    """API健康检查"""
    return jsonify({
        'success': True,
        'message': 'API服务运行正常',
        'version': '1.0.0'
    }), 200

# 保留原有的文件上传接口
@app.route('/upload', methods=['POST'])
def upload_file():
    """
    文件上传接口。
    """
    if 'file' not in request.files:
        return jsonify({'error': 'No file part'}), 400

    file = request.files['file']
    if file.filename == '':
        return jsonify({'error': 'No selected file'}), 400

    file_path = os.path.join(UPLOAD_FOLDER, file.filename)
    file.save(file_path)

    try:
        # 解析文件内容
        content = parse_file(file_path)
        slices = content.split('\n\n')  # 按段落切片

        # 这里可以保存到数据库或返回解析结果
        return jsonify({
            'message': 'File uploaded and parsed successfully',
            'filename': file.filename,
            'slices_count': len(slices)
        }), 201

    except Exception as e:
        return jsonify({'error': str(e)}), 500

# 保留原有的Socket.IO功能
@app.route('/test-socket', methods=['GET'])
def test_socket():
    return {"message": "Socket server is running"}, 200

@socketio.on('clientMessage')
def handle_client_message(message):
    print(f"Received from client: {message}")
    socketio.emit('serverMessage', f"Echo: {message}")

# 全局错误处理
@app.errorhandler(404)
def not_found(error):
    return jsonify({
        'success': False,
        'error': '接口不存在'
    }), 404

@app.errorhandler(500)
def internal_error(error):
    return jsonify({
        'success': False,
        'error': '服务器内部错误'
    }), 500

# 初始化数据库
# @app.before_request
# def create_tables():
#     """在第一次请求前初始化数据库"""
#     try:
#         init_database()
#         print("数据库初始化完成")
#     except Exception as e:
#         print(f"数据库初始化失败: {e}")

if __name__ == '__main__':
    # 在开发环境中可以手动初始化数据库
    try:
        init_database()
        print("数据库连接成功，表结构已创建")
    except Exception as e:
        print(f"数据库初始化失败: {e}")
    
    print("启动Flask应用...")
    print("API端点:")
    print("- 知识库: /api/v1/knowledge-bases")
    print("- 文档: /api/v1/documents")
    print("- 用户认证: /api/v1/auth")
    print("- 健康检查: /api/v1/health")
    
    socketio.run(app, host='0.0.0.0', port=3001, debug=True)
